﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessLayer
{
    public class DelegateDAL
    {
        StationeryInventoryEntities1 ent;

        public DelegateDAL()
        {
            ent = new StationeryInventoryEntities1();
        }

        public Department getDeptInfoByUserName(String userName)
        {
            Department d = ent.Departments.FirstOrDefault(x => x.Employee.User.UserName == userName);
            return d;
        }

        public ActingManager getActingManagerInfoByID(int actingManagerID)
        {
            ActingManager am = ent.ActingManagers.FirstOrDefault(x => x.EmployeeID == actingManagerID && x.EndDate == null);
            return am;
        }

        public List<Employee> getEmpListByUserName(String userName)
        {
            Employee e = ent.Employees.FirstOrDefault(x => x.User.UserName == userName);
            //get all the employee list in one dept withoud dept Head
            var empList = (from x in ent.Employees where x.DeptID == e.DeptID && x.User.UserName!=userName select x);
            return empList.ToList();
        }

        public int saveToAM(int empId, DateTime startDate, String reason)
        {
            Employee e = ent.Employees.FirstOrDefault(x=> x.EmployeeID==empId);
            ActingManager am = new ActingManager();
            am.EmployeeID = empId;
            am.Reason = reason;
            am.StartDate = startDate;
            am.DeptID = e.DeptID;
            ent.ActingManagers.Add(am);
            ent.SaveChanges();
            int delegationID = am.DelegationID;

            String deptID = e.DeptID;
            Department d = ent.Departments.FirstOrDefault(x => x.DeptID == deptID);
            d.ActingManagerID = empId;
            ent.SaveChanges();

            return delegationID;

        }
        public int revoke(int empId)
        {
            ActingManager am = ent.ActingManagers.FirstOrDefault(x => x.EmployeeID == empId && x.EndDate == null);
            am.EndDate = DateTime.Today;
            ent.SaveChanges();

            String deptID = am.Employee.DeptID;
            Department d = ent.Departments.FirstOrDefault(x => x.DeptID == deptID);
            d.ActingManagerID = null;
            ent.SaveChanges();

            return am.DelegationID;

        }

        public ActingManager getDelegationInfo(int dId)
        {
            ActingManager am = ent.ActingManagers.FirstOrDefault(x => x.DelegationID == dId);
            return am;
        }
    }
}
